package com.example.springbootdemo.defination

import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

//由業務程序員定義
enum class CustomError(val code: Int, val message: String) {
    UnknownError(10000, "未知錯誤，請聯繫管理員"),
    CustomError1(10001, "自定義錯誤1"),
    CustomError2(10002, "自定義錯誤2")
}

data class CustomException(val customError: CustomError, val result: Any? = null) : Exception(customError.message)


//由接口程序員定義
/**
 * @param data 返回需要返回的數據，可空
 * @param customException 正常情況不用此構造方法
 */
data class CustomResponse(var data: Any? = null) {
    var code: Int = 0
    var message: String = "OK"

    constructor(customException: CustomException) : this(
            customException.result
    ) {
        code = customException.customError.code
        message = customException.customError.message
    }
}

@RestControllerAdvice
class ExceptionHandler() {
    @ExceptionHandler(RuntimeException::class)
    fun handleRuntimeException(e: Exception) = CustomResponse(CustomException(CustomError.UnknownError))

    @ExceptionHandler(CustomException::class)
    fun handleCustomException(ce: CustomException) = CustomResponse(ce)
}